import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CharacterEncodingFilter implements Filter {
    private static String encoding;
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        request.setCharacterEncoding(encoding);
        response.setContentType("text/http;charset="+encoding);
        System.out.println("过滤器已生效");
        chain.doFilter(req, resp);
    }

    //这是初始化会执行的代码，大项目要改直接改xml配置中的encoding值来实现字符适配，而不是重新运行
    public void init(FilterConfig config) throws ServletException {
        encoding = config.getInitParameter("encoding");
        System.out.println("encoding:"+encoding);
    }

}
